package com.qubuyer.business.home.fragment

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import com.qubuyer.R
import com.qubuyer.business.good.activity.SearchGoodActivity
import com.qubuyer.business.home.activity.ScanActivity
import com.qubuyer.business.home.adapter.HomeAdapter
import com.qubuyer.business.home.view.*
import com.qubuyer.business.mine.activity.MessageListActivity
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.customview.HomeGoodItemDecoration
import com.qubuyer.databinding.FragmentHomeBinding
import com.qubuyer.ext.checkLogin
import com.qubuyer.utils.NavigationUtil
import com.qubuyer.utils.StatusBarUtil

class HomeFragment : MVVMFragment<FragmentHomeBinding, HomeViewModel>() {

    override val layoutId: Int
        get() = R.layout.fragment_home

    override val viewModel: HomeViewModel by injectVMByFragment()

    override fun onDataBinding(dataBinding: FragmentHomeBinding) {
        dataBinding.host = this
    }

    private lateinit var mAdapter: HomeAdapter
    private var mOverallXScroll = 0
    private var mLayoutManager: GridLayoutManager? = null

    private lateinit var bannerItemView: BannerItemView
    private lateinit var cateItemView: CateItemView
    private lateinit var saleTopItemView: SaleTopItemView
    private lateinit var specItemView: SpecItemView
    private lateinit var superReturnItemView: SuperReturnItemView
    private lateinit var dailyDiscountItemView: DailyDiscountItemView
    private lateinit var goodsTopItemView: GoodsTopItemView

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        ob()

        initToolbar()
        initPullToRefresh()
        initRecyclerView()
        viewDataBinding.srlContent.autoRefresh()
    }

    private fun ob() {
        viewModel.bannerData.observe(viewLifecycleOwner, {
            bannerItemView.onDataSet(it)
        })
        viewModel.cateData.observe(viewLifecycleOwner, {
            cateItemView.onDataSet(it)
        })
        viewModel.saleTopData.observe(viewLifecycleOwner, {
            saleTopItemView.onDataSet(it)
        })
        viewModel.userData.observe(viewLifecycleOwner, {
            saleTopItemView.bindUser(it)
        })
        viewModel.choiceData.observe(viewLifecycleOwner, {
            specItemView.bindChoiceList(it)
        })
        viewModel.limitData.observe(viewLifecycleOwner, {
            specItemView.bindLimitList(it)
        })
        viewModel.specData.observe(viewLifecycleOwner, {
            specItemView.onDataSet(it)
        })
        viewModel.publishData.observe(viewLifecycleOwner, {
            specItemView.bindPublishList(it)
        })
        viewModel.superReturnData.observe(viewLifecycleOwner, {
            superReturnItemView.onDataSet(it)
        })
        viewModel.dailyDiscountData.observe(viewLifecycleOwner, {
            dailyDiscountItemView.onDataSet(it)
        })
        viewModel.unreadMsgCount.observe(viewLifecycleOwner, {
            viewDataBinding.tvMessageCount.isVisible = it > 0
            viewDataBinding.tvMessageCount.text = it.toString()
        })
    }

    private fun initToolbar() {
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.setMargins(0, StatusBarUtil.getStatusBarHeight(), 0, 0)
        viewDataBinding.rlToolbar.layoutParams = layoutParams
    }

    private fun initPullToRefresh() {
        viewDataBinding.srlContent.setOnRefreshListener { refreshLayout ->
            refreshLayout.setNoMoreData(false)
            viewModel.refresh { success, dataList, _, _ ->
                if (success) {
                    mAdapter.setDataList(dataList)
                    viewDataBinding.srlContent.finishRefresh(true)
                } else {
                    viewDataBinding.srlContent.finishRefresh(false)
                }
            }
            mOverallXScroll = 0
        }
        viewDataBinding.srlContent.setOnLoadMoreListener {
            viewModel.loadMore { success, dataList, _, _ ->
                if (success) {
                    mAdapter.addDataList(dataList)
                    viewDataBinding.srlContent.finishLoadMore(0, true, dataList?.size ?: 0 < 10)
                } else {
                    viewDataBinding.srlContent.finishLoadMore(0, false, true)
                }
            }
        }
        viewDataBinding.srlContent.setEnableScrollContentWhenLoaded(true)
    }

    private fun initRecyclerView() {
        mAdapter = HomeAdapter()
        mLayoutManager = GridLayoutManager(mContext, 2).apply {
            spanSizeLookup = object : SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    if (mAdapter.isHeader(position)) {
                        return mLayoutManager!!.spanCount
                    }
                    return 1
                }
            }
        }
        viewDataBinding.rvContent.apply {
            itemAnimator = null
            layoutManager = mLayoutManager
            adapter = mAdapter
            addItemDecoration(HomeGoodItemDecoration())
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    mOverallXScroll += dy
                    setToolbarBackgroundResource()
                }
            })
        }
        bannerItemView = BannerItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_banner)
        cateItemView = CateItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_cate)
        saleTopItemView = SaleTopItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_sale_top)
        specItemView = SpecItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_special)
        superReturnItemView = SuperReturnItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_super_return)
        dailyDiscountItemView = DailyDiscountItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_dailydiscount)
        goodsTopItemView = GoodsTopItemView(viewLifecycleOwner, mContext, viewDataBinding.rvContent, R.layout.home_item_good_top)
        mAdapter.addHeader(bannerItemView)
        mAdapter.addHeader(cateItemView)
        mAdapter.addHeader(saleTopItemView)
        mAdapter.addHeader(specItemView)
        mAdapter.addHeader(superReturnItemView)
        mAdapter.addHeader(dailyDiscountItemView)
        mAdapter.addHeader(goodsTopItemView)
    }

    private fun setToolbarBackgroundResource() {
        viewDataBinding.ivScrollTop.isVisible = mOverallXScroll > 0
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden) {
            setToolbarBackgroundResource()
        }
    }

    override fun hideProgressDialog() {
        viewDataBinding.srlContent.finishRefresh()
        viewDataBinding.srlContent.finishLoadMore()
        super.hideProgressDialog()
    }

    override fun onResume() {
        super.onResume()
        setToolbarBackgroundResource()
    }

    fun onClick(v: View) {
        when (v.id) {
            R.id.iv_scan -> {
                mContext.checkPermissions(listOf(Manifest.permission.CAMERA)) {
                    NavigationUtil.overlay(mContext, ScanActivity::class.java)
                }
            }
            R.id.ll_search -> NavigationUtil.overlay(mContext, SearchGoodActivity::class.java)
            R.id.fl_message -> checkLogin {
                NavigationUtil.overlay(mContext, MessageListActivity::class.java)
            }
            R.id.iv_scroll_top -> {
                mOverallXScroll = 0
                viewDataBinding.rvContent.scrollToPosition(0)
            }
        }
    }
}